<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="视频名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="分类" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="视频分类"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in typeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="视频状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in statusArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
          >删除</el-button
        >
      </el-col>
       <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:role:export']"
            >导出</el-button
          >
        </el-col> 
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="videoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="视频名称"
        prop="title"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="上传者"
        prop="createBy"
        align="center"
        :show-overflow-tooltip="true"
        width="150"
      />
      <!-- <el-table-column
        label="分类"
        prop="type"
        align="center"
        :show-overflow-tooltip="true"
        width="150"
      /> -->
      <!-- <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column> -->

      <el-table-column
        label="审核结果"
        prop="auditState"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-tag :type="tagType(scope.row.auditState)">{{
            tagText(scope.row.auditState)
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="视频描述"
        prop="description"
        :show-overflow-tooltip="true"
        width="190"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:role:edit']"
            >查看评论</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增视频dialog -->
    <el-dialog
      :title="dialogStatus.title"
      :visible.sync="dialogStatus.visible"
      width="1000px"
      append-to-body
      center
      @close="closeDialog"
    >
      <el-table
        v-loading="loading"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="id"
        :data="commentList"
        :lazy="true"
        :load="load"
      >
        <el-table-column
          label="评论者"
          prop="createBy"
          width="120"
          :show-overflow-tooltip="true"
        />

        <!-- <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column> -->

        <!-- <el-table-column
          label="审核结果"
          prop="auditState"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-tag :type="tagType(scope.row.auditState)">{{
              tagText(scope.row.auditState)
            }}</el-tag>
          </template>
        </el-table-column> -->

        <el-table-column
          label="评论内容"
          prop="content"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleDetail(scope.row)"
              v-hasPermi="['system:role:edit']"
              >隐藏</el-button
            > -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleDeleteComment(scope.row)"
              v-hasPermi="['system:role:edit']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer" v-if="!dialogStatus.isDetail">
        <el-button type="primary" @click="handleSubmitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传进度 -->
    <el-dialog
      :visible.sync="dialogStatus.isUploading"
      title="上传中"
      width="14%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="closeUploading"
    >
      <div style="display: flex; text-align: center; justify-content: center">
        <el-progress
          type="dashboard"
          :percentage="percentage"
          :color="colors"
        ></el-progress>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUploadAuth as getUploadAuthApi,
  getVideoList as getVideoListApi,
  getPlayAuth as getPlayAuthApi,
  getVideoDetail as getVideoDetailApi,
  updateVideo as updateVideoApi,
  deleteVideo as deleteVideoApi,
} from "../../../api/video/videoList";
import {
  getCommentDetail as getCommentDetailApi,
  deleteComment as deleteCommentApi,
} from "../../../api/video/comment";
import { Notification, MessageBox, Message, Loading } from "element-ui";

import to from "await-to-js";
export default {
  name: "videoList",
  data() {
    return {
      queryParams: {
        name: "",
        status: "",
        type: "",
        pageSize: 10,
        auditState: "1",
        pageNum: 1,
        orderByColumn: "createTime",
        isAsc: "desc",
      },
      queryCommentParams: {
        targetId: "",
        pageSize: 10,
        pageNum: 1,
        orderByColumn: "createTime",
        isAsc: "desc",
      },
      // getAuthParams: {
      //   fileName: "",
      //   title: "",
      // },
      // 多选
      multiple: true,
      // 单选状态
      single: true,
      ids: [],
      // 是否展示search
      showSearch: true,
      // 加载状态
      loading: false,
      dialogLoading: false,
      // 视频列表
      videoList: [],
      commentList: [],
      commentTotal: 0,
      // 列表总数
      total: 0,
      // 将要上传的文件
      file: "",
      fileList: [],
      // 视频上传进度
      percentage: 0,
      // 视频播放器
      videoPlayer: "",
      initDialogStatus: {
        isDetail: false,
        isUpdate: false,
        isAdd: false,
        visible: false,
        isUploading: false,
        title: "",
      },
      dialogStatus: {
        isDetail: false,
        isUpdate: false,
        isAdd: false,
        visible: false,
        isUploading: false,
        title: "",
      },
      dialogData: {
        title: "",
        description: "",
        type: "",
        fileName: "",
        status: "0",
      },
      typeArr: [
        {
          label: "option1",
          value: "1",
        },
        {
          label: "option2",
          value: "2",
        },
        {
          label: "option3",
          value: "3",
        },
      ],
      statusArr: [
        {
          label: "停用",
          value: "1",
        },
        {
          label: "正常",
          value: "0",
        },
      ],
      rules: {
        title: [
          { required: true, message: "视频标题不能为空！", trigger: "blur" },
        ],
        status: [
          { required: true, message: "状态为必选项！", trigger: "blur" },
        ],
      },
      colors: [
        { color: "#f56c6c", percentage: 20 },
        { color: "#e6a23c", percentage: 40 },
        { color: "#5cb87a", percentage: 60 },
        { color: "#1989fa", percentage: 80 },
        { color: "#6f7ad3", percentage: 100 },
      ],
    };
  },
  methods: {
    // 重置
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 搜索
    handleQuery() {
      this.getList();
    },
    // 获取列表
    async getList() {
      this.loading = true;
      const [err, res] = await to(getVideoListApi(this.queryParams));
      if (!err) {
        console.log(res);
        this.videoList = res.rows;
        this.total = Number(res.total);
        this.loading = false;
      } else {
        Message.error("获取视频列表失败");
        this.loading = false;
      }
    },
    // 获取资源详情
    async getVideoDetail(id) {
      const [err, res] = await to(getVideoDetailApi(id));
      if (!err) {
        console.log(res);
        this.dialogData = res.data;
      }
    },
    // 遍历树形节点
    traverse(node) {
      if (node === null) {
        return;
      }
      node.content = node.comment.content;
      node.createTime = node.comment.createTime;
      node.createBy = node.comment.createBy;
      console.log(node); // 访问当前节点

      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          this.traverse(node.children[i]); // 递归遍历子节点
        }
      }
    },
    // 点击视频详情按钮
    async handleDetail(row) {
      this.dialogLoading = true;
      this.dialogStatus.visible = true;
      this.dialogStatus.isDetail = true;
      this.dialogStatus.title = "评论详情";
      this.queryCommentParams.targetId = row.videoId;
      // 获取视频详情
      const [err, res] = await to(getCommentDetailApi(this.queryCommentParams));
      if (!err) {
        this.commentList = res.rows;
        this.commentList.forEach((item) => {
          this.traverse(item);
        });
        this.dialogLoading = false;
      } else {
        this.dialogLoading = false;
      }
    },
    // 添加视频按钮
    handleAdd() {
      this.dialogStatus.visible = true;
      this.dialogStatus.isAdd = true;
      this.dialogStatus.title = "新增视频";
    },
    // 修改视频按钮
    async handleUpdate(row) {
      this.dialogStatus.visible = true;
      this.dialogStatus.isUpdate = true;
      this.dialogStatus.title = "更新视频";
      this.dialogLoading = true;
      let _id;
      if (row.videoId) {
        _id = row.videoId;
      } else {
        _id = this.ids[0];
      }
      // 获取视频详情
      await this.getVideoDetail(_id);
      // 获取播放凭证
      const [err, res] = await to(getPlayAuthApi(_id));
      if (!err) {
        console.log(res);
        // await nextTick(() => {
        this.videoPlayer = new Aliplayer({
          id: "player-" + _id,
          width: "100%",
          vid: res.data.vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
          playauth: res.data.playAuth, //必选参数。音视频播放凭证。
          autoplay: true,
          preload: true,
        });
        // });
        this.dialogLoading = false;
      } else {
        Message.error("获取播放凭证失败！");
        this.dialogLoading = false;
      }
    },
    // 修改视频状态
    async handleStatusChange(row) {
      console.log(row);
      this.loading = true;
      row.status === "1" ? "0" : "1";
      const [err, res] = await to(updateVideoApi(row));
      if (!err) {
        // 更新成功
        console.log(res);
        Message.success("更改成功");
        this.getList();
        this.loading = false;
      } else {
        Message.error("更改失败");
        this.getList();
        this.loading = false;
      }
    },
    // 删除按钮
    async handleDeleteComment(row) {
      console.log(row);
      this.loading = true;
      const message =
        '是否确认删除用户"' + row.comment.createBy + '"的该条评论?';
      const [err, res] = await to(
        this.$confirm(message, "提示", {
          confirmButtonText: "确定",
          handleCancelButtonText: "取消",
          type: "warning",
        })
      );
      if (!err) {
        if (row.id) {
          const [err] = await to(deleteCommentApi(row.id));
          if (!err) {
            Message.success("删除成功");
            const [err, res] = await to(
              getCommentDetailApi(this.queryCommentParams)
            );
            if (!err) {
              this.commentList = res.rows;
              this.commentList.forEach((item) => {
                this.traverse(item);
              });
              this.loading = false;
            } else {
              this.loading = false;
            }
          } else {
            Message.error("删除失败");
            // this.getList();
            this.loading = false;
          }
        } else {
          const [err] = await to(deleteVideoApi(this.ids));
          if (!err) {
            Message.success("删除成功");
            this.getList();
            this.loading = false;
          } else {
            Message.error("删除失败");
            this.getList();
            this.loading = false;
          }
        }
      } else {
        Message.info("取消成功");
        this.loading = false;
      }
    },
    // 列表勾选
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.videoId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      console.log(this.ids);
    },
    // dialog提交按钮
    handleSubmitForm() {
      this.$refs["form"].validate(async (vilid) => {
        if (vilid) {
          if (this.dialogData.videoId) {
            // 有id为更新
            const [err, res] = await to(updateVideoApi(this.dialogData));
            if (!err) {
              // 更新成功
              console.log(res);
              Message.success("更新成功");
              this.dialogStatus.visible = false;
              this.getList();
            } else {
              Message.error("更新失败");
            }
          } else {
            // 无id为新增
            if (this.dialogData.fileName === "") {
              Message.info("你未选择任何视频文件，请先添加视频文件！");
            } else {
              this.dialogStatus.isUploading = true;
              this.sendOSS();
            }
          }
        }
      });
    },
    // 取消按钮
    handleCancel() {
      this.dialogStatus.visible = false;
    },
    // 关闭dialog
    closeDialog() {
      this.loading = false;
      this.dialogLoading = false;
      this.fileList = [];
      this.dialogStatus = Object.assign({}, this.initDialogStatus);
      this.dialogData = {
        title: "",
        description: "",
        type: "",
        fileName: "",
        status: "0",
      };
      // 清空播放器
      if (this.videoPlayer != "") {
        this.videoPlayer.dispose();
      }
      console.log(this.dialogStatus);
    },
    tagType(typeCode) {
      if (typeCode === "0") {
        return "info";
      } else if (typeCode === "1") {
        return "success";
      } else {
        return "danger";
      }
    },
    tagText(typeCode) {
      if (typeCode === "0") {
        return "未审核";
      } else if (typeCode === "1") {
        return "审核通过";
      } else {
        return "被驳回";
      }
    },
    load(row, treeNode, resolve) {
      console.log(row, treeNode, resolve);
      setTimeout(() => {
        resolve([
          {
            id: 31,
            date: "2016-05-01",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1519 弄",
          },
          {
            id: 32,
            date: "2016-05-01",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1519 弄",
          },
        ]);
      }, 1000);
    },
  },
  created() {
    this.getList();
  },
};
</script>
